class TaskManager {
  constructor(maxTasks) {
    this.maxTasks = maxTasks;
    this.activeTasks = new Map(); // 使用Map来存储正在进行的任务，使得根据taskId快速删除
    this.waitingTasks = [];
    this.drainCallbacks = []; // 存储drain回调的数组
  }

  // 注册当所有任务都完成时的回调函数
  drain(callback) {
    this.drainCallbacks.push(callback);
  }

  // 移除指定的回调函数
  offDrain(callback) {
    const index = this.drainCallbacks.indexOf(callback);
    if (index !== -1) {
      this.drainCallbacks.splice(index, 1);
    }
  }

  add(taskId, task) {
    return new Promise((resolve, reject) => {
      const taskObj = { task, taskId, resolve, reject };

      if (this.activeTasks.size < this.maxTasks) {
        this._run(taskObj);
      } else {
        this.waitingTasks.push(taskObj);
      }
    });
  }
  async _run(taskObj) {
    this.activeTasks.set(taskObj.taskId, taskObj);
    try {
      const result = await taskObj.task();
      taskObj.resolve(result);
    } catch (error) {
      taskObj.reject(error);
    } finally {
      this.activeTasks.delete(taskObj.taskId);
      if (this.waitingTasks.length > 0) {
        this._run(this.waitingTasks.shift());
      } else if (this.activeTasks.size === 0) {
        // 检查是否所有任务都完成了
        this.drainCallbacks.forEach((callback) => callback()); // 执行所有的drain回调
      }
    }
  }

  removeTask(taskId) {
    if (this.activeTasks.has(taskId)) {
      // 如果任务正在执行，可以将其标记为中断或其他操作。
      // 但基于现有的Promise架构，我们不能从外部"取消"一个已经运行的Promise。
      console.warn(
        `Task ${taskId} is currently running and cannot be immediately removed.`
      );
    } else {
      const index = this.waitingTasks.findIndex(
        (taskObj) => taskObj.taskId === taskId
      );
      if (index !== -1) {
        const [taskObj] = this.waitingTasks.splice(index, 1);
        taskObj.reject(
          new Error(`Task ${taskId} has been removed before execution.`)
        );
      }
    }
  }

  clearAllTasks() {
    // 通知所有等待的任务它们被取消了
    // for (let taskObj of this.waitingTasks) {
    //   taskObj.reject(
    //     new Error(`Task ${taskObj.taskId} has been removed before execution.`)
    //   );
    // }
    this.waitingTasks = []; // 清空等待任务队列

    // 通知所有活动的任务它们被取消了（虽然不能真正取消正在运行的Promise）
    for (let [taskId, taskObj] of this.activeTasks) {
      console.warn(
        `Task ${taskId} is currently running and cannot be immediately removed.`
      );
      // 如果你的任务支持取消，你可能想在这里调用它
      // 例如：taskObj.cancel();
    }
    this.activeTasks.clear(); // 清空活动任务Map
  }
}

export default TaskManager;

// 使用示例
// const manager = new TaskManager(2);

// const sampleTask = (delay) => {
//   return new Promise((resolve) => {
//     setTimeout(() => {
//       console.log(`Task finished after ${delay} ms`);
//       resolve();
//     }, delay);
//   });
// };

// manager.add("task1", () => sampleTask(1000));
// manager.add("task2", () => sampleTask(2000));
// manager
//   .add("task3", () => sampleTask(3000))
//   .catch((error) => {
//     console.log("Error for task3:", error.message);
//   });

// // 删除任务：
// manager.removeTask("task3");
